package com.fw.cost.api.controller.researchCost;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.*;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.openxml4j.util.ZipSecureFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.style.column.SimpleColumnWidthStyleStrategy;
import com.fw.cost.api.config.IgnoreLoginInterceptor;
import com.fw.cost.commons.excel.*;
import com.fw.cost.model.entity.researchCost.ResearchProjCostSummaryModel;
import com.fw.cost.producer.service.researchCost.IResearchProjCostSummaryService;
import com.fw.cost.model.exception.BusinessException;
import com.fw.cost.model.exception.ExceptionEnum;
import com.fw.cost.model.form.BussResultForm;
import com.fw.cost.model.form.basic.*;
import com.fw.cost.model.metadata.ApiPageResult;
import com.fw.cost.model.metadata.ApiResult;
import com.fw.cost.model.util.enums.ModuleEnum;
import com.fw.cost.model.vo.costCollection.AnalyzeImportResultVo;
import com.fw.cost.producer.service.basic.IResearchProjCostSummaryService;
import com.fw.cost.producer.service.exportLog.IExportService;
import com.google.common.collect.Lists;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;


/**
* <b><code></code></b>
* <p/>
*
*  科研项目成本汇总表控制层
*
* <p/>
* <b>Creation Time:</b> 2024/09/27 09:11:36
*
* @author 
* @version ${classInfo.version}
*/
@RestController
@Api(tags = "")
@RequestMapping("/researchProjCostSummary")
@RequiredArgsConstructor
public class ResearchProjCostSummaryController {

    private static final Logger log = LoggerFactory.getLogger(ResearchProjCostSummaryController.class);
    private final IResearchProjCostSummaryService researchProjCostSummaryService;
    private final IExportService exportService;


    /**
    * 获取 科研项目成本汇总表列表
    *
    * @param queryForm
    * @return ApiResult
    * @Date 14:11 2024/8/12
    * @since ${classInfo.version}
    */
    @ApiOperation(" 科研项目成本汇总表列表")
    @PostMapping("/getResearchProjCostSummaryList")
    public ApiResult getResearchProjCostSummaryList(@RequestBody ResearchProjCostSummaryQueryForm queryForm) {
        ApiPageResult list = researchProjCostSummaryService.getResearchProjCostSummaryList(queryForm);
        return ApiResult.success(list);
    }

    /**
    * 新增、更新 科研项目成本汇总表
    *
    * @param addForm
    * @return ApiResult
    * @Date 14:39 2024/8/12
    * @since ${classInfo.version}
    */
    @ApiOperation("新增、更新 科研项目成本汇总表")
    @PostMapping("/addOrUpdateResearchProjCostSummary")
    public ApiResult addOrUpdateResearchProjCostSummary(@RequestBody ResearchProjCostSummaryAddForm addForm) {
        if (incomeProjectAddForm == null) {
            return ApiResult.error(ExceptionEnum.INTERNAL_SERVER_ERROR.getCode(), "传入参数为空！");
        }

        try {
            researchProjCostSummaryService.addOrUpdateResearchProjCostSummary(addForm);
        } catch (Exception e) {
            log.info("添加/更新 科研项目成本汇总表失败");
            return ApiResult.error(ExceptionEnum.INTERNAL_SERVER_ERROR.getCode(), e.getMessage());
        }
        return ApiResult.success();
    }

    /**
    * 获取 科研项目成本汇总表对象
    *
    * @param id
    * @return ApiResult
    * @Date 14:52 2024/8/12
    * @since ${classInfo.version}
    */
    @ApiOperation("获取 科研项目成本汇总表对象")
    @PostMapping("/getResearchProjCostSummary")
    @ApiImplicitParams({@ApiImplicitParam(type = "id", name = "id", value = "主键ID", required = true)})
    public ApiResult getResearchProjCostSummary(String id) {
        if (StringUtils.isBlank(id)) {
            return ApiResult.error(ExceptionEnum.INTERNAL_SERVER_ERROR.getCode(), "主键ID为空！");
        }
        ResearchProjCostSummaryModel model = researchProjCostSummaryService.getById(id);
        return ApiResult.success(model);
    }

    /**
    * 批量删除 科研项目成本汇总表对象
    *
    * @param delForm
    * @return ApiResult
    * @Date 15:09 2024/8/12
    * @since ${classInfo.version}
    */
    @ApiOperation("批量删除 科研项目成本汇总表对象")
    @PostMapping("/batchDeleteResearchProjCostSummary")
    @ApiImplicitParams({@ApiImplicitParam(type = "idlist", name = "idlist", value = "主键ID集合", required = true)})
    public ApiResult batchDeleteResearchProjCostSummary(@RequestBody ResearchProjCostSummaryDelForm delForm) {
        if (delForm == null) {
            return ApiResult.error(ExceptionEnum.INTERNAL_SERVER_ERROR.getCode(), "主键ID或者主键ID列表为空！");
        }
    researchProjCostSummaryService.delByResearchProjCostSummaryList(delForm.getIdList(),delForm.getPeriod());
    return ApiResult.success();
}

/**
* 下载 科研项目成本汇总表模板
*
* @param response
* @return void
* @Date 16:22 2024/8/12
* @since ${classInfo.version}
*/
@IgnoreLoginInterceptor
@ApiOperation("下载 科研项目成本汇总表模板")
@GetMapping(value = "/downloadImportTemplate", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
public void downloadImportTemplate(HttpServletResponse response) throws IOException {
    List<List<String>> heads = new ArrayList<>();
    heads.add(Collections.singletonList("* 科研项目成本汇总表编号"));
    heads.add(Collections.singletonList("* 科研项目成本汇总表名称"));
    //下载模板
    response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" +
    URLEncoder.encode(" 科研项目成本汇总表导入模板.xlsx", StandardCharsets.UTF_8.name()));
    response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
    //生成excel文件
    EasyExcel.write(response.getOutputStream()).excludeColumnFiledNames(Collections.singleton("result"))
    .head(heads)
    .registerWriteHandler(ExcelHelper.getHeadStyle())
    .registerWriteHandler(new I18nExportCellHandler())
    .registerWriteHandler(new MustHeaderCellHandler())
    .inMemory(true).sheet(" 科研项目成本汇总表").doWrite(Collections.EMPTY_LIST);
    }

    
    /**
    * 导入 科研项目成本汇总表分析
    *
    * @param file            导入文件
    * @param basicImportForm 导入项目分类Form
    * @return ApiResult
    * @Date 16:40 2024/8/12
    * @since ${classInfo.version}
    */
    @ApiOperation("导入 科研项目成本汇总表分析")
    @PostMapping("/importAnalysis")
    public ApiResult importAnalysis(MultipartFile file, BasicImportForm basicImportForm) throws IOException {
    //检查导入文件
    List<ResearchProjCostSummaryImportExcelForm> importList = getImportData(file);
        //导入分析
        AnalyzeImportResultVo analyzeImportResultVo = researchProjCostSummaryService.importAnalysis(basicImportForm,
        importList);
        return ApiResult.success(analyzeImportResultVo);
    }

    /**
    * 获取导入数据
    *
    * @param file
    * @return List<ResearchProjCostSummaryImportExcelForm>
    * @Date 10:03 2024/8/13
    * @since ${classInfo.version}
    */
    public List<ResearchProjCostSummaryImportExcelForm> getImportData(MultipartFile file) throws IOException {
        //校验文件
        ImportUtils.checkImportFile(file);
        //构建表头heads
        List<String> heads = Lists.newArrayList("* 科研项目成本汇总表编号", "* 科研项目成本汇总表名称");
        ResearchProjCostSummaryImportListener incomeProjectImportListener = readExcel(file);
        //解析heads
        Map<Integer, String> parseHeads = incomeProjectImportListener.getHead();
        ImportUtils.parseMatchImportHeads(heads, parseHeads);
        //导入的数据
        return incomeProjectImportListener.getList();
    }

    /**
    * 导入 科研项目成本汇总表
    *
    * @param file 需要解析的文件
    * @param basicImportForm
    * @return ApiResult
    * @Date 11:16 2024/8/13
    * @since ${classInfo.version}
    */
    @ApiOperation("导入 科研项目成本汇总表")
    @PostMapping("/importResearchProjCostSummary")
    public ApiResult importResearchProjCostSummary(MultipartFile file, BasicImportForm basicImportForm) throws IOException {
    //检查导入文件
    List<ResearchProjCostSummaryImportExcelForm> importList = getImportData(file);
        //导入
        try {
             researchProjCostSummaryService.importResearchProjCostSummary(basicImportForm, importList);
        } catch (Exception e) {
            return ApiResult.error(ExceptionEnum.INTERNAL_SERVER_ERROR.getCode(),"导入失败");
        }
        return ApiResult.success("导入成功");
    }

                        
    /**
    * 导出
    *
    * @param incomeProjectQueryForm
    * @return ApiResult
    * @Date 19:45 2024/8/14
    * @since ${classInfo.version}
    */
    @ApiOperation("导出")
    @PostMapping("/export")
    public ApiResult export(@RequestBody ResearchProjCostSummaryQueryForm incomeProjectQueryForm){
    //查询列表
    List<ResearchProjCostSummaryModel> list = researchProjCostSummaryService.getListByPeriod(incomeProjectQueryForm);
        if(CollectionUtils.isEmpty(list)){
        return ApiResult.error(new BusinessException("暂无数据可导出"));
        }

        ExportMetaDataForm exportMetaDataForm = ExportMetaDataForm.builder()
        .sheetName(" 科研项目成本汇总表")
        .returnClass(ResearchProjCostSummaryModel.class)
        .moduleEnum(ModuleEnum.INCOME_PROJECT_RESULT)
        .cellWriteHandlers(Lists.newArrayList(ExcelHelper.getHeadStyle(),new SimpleColumnWidthStyleStrategy(25)))
        .excludeColumnFiledNames(Collections.emptyList())
        .consumerData(()->list)
        .build();
        boolean exportResult = exportService.export(exportMetaDataForm);
        if(!exportResult){
        return ApiResult.error(ExceptionEnum.INTERNAL_SERVER_ERROR.getCode(),"导出失败");
        }
        return ApiResult.success("导出中，请到结果中查看");
    }

    /**
    * 检查复制上一会计周期
    *
    * @param basicCopyPreviousPeriodForm
    * @return ApiResult
    * @Date 9:33 2024/8/15
    * @since ${classInfo.version}
    */
    @ApiOperation("检查复制上一会计周期")
    @PostMapping("/checkCopyPreviousPeriodData")
    public ApiResult checkCopyLastFiscalYearData(@RequestBody BasicCopyPreviousPeriodForm basicCopyPreviousPeriodForm){
        BussResultForm bussResultForm = researchProjCostSummaryService.checkCopyLastFiscalYearData(basicCopyPreviousPeriodForm);
        return ApiResult.success(bussResultForm);
    }

    /**
    * 复制上一周期
    *
    * @param basicCopyPreviousPeriodForm
    * @return ApiResult
    * @Date 9:33 2024/8/15
    * @since ${classInfo.version}
    */
    @ApiOperation("复制上一会计周期")
    @PostMapping("/copyPreviousPeriod")
    public ApiResult copyPreviousPeriod(@RequestBody BasicCopyPreviousPeriodForm basicCopyPreviousPeriodForm){
        researchProjCostSummaryService.copyPreviousPeriod(basicCopyPreviousPeriodForm);
        return ApiResult.success("复制成功");
    }                            

}
